import Button from "@ui/RJMart/button";
import Textarea from "@ui/RJMart/textarea";
import message from "@ui/RJMart/message";
import ToastUtils from "@page/common/utils/ToastUtils";
import ZenModal from "@module/../components/ZenUI/ZenModal/ZenModal";

import REST from "@module/Rest";
import { default as U } from "@module/Uts";

import "./style.scss";
class ProcurementMoney extends React.Component {
    constructor(props) {
        super(props);

        //状态值
        this.state = {
            textareaValue: "",
            hasLabel:this.props.hasLabel
        };
        this.orgId = Uts.getCookie("orgId");
        this.totalPrice = 0;
    }

    //设置textareaValue
    changeValue(e) {
        this.setState({
            textareaValue: e
        });
        console.log(this.state);
    }

    // totalCount = data => {
    //     let count = 0;
    //     if ($state.params.groupbuyingId) {
    //         count = 1
    //     } else {
    //         if(data&&data.length) {
    //             data.forEach((v, k) => {
    //                 v.cart &&
    //                     v.cart.forEach((v1, k1) => {
    //                         count++;
    //                     });
    //             });
    //         }
    //     }
    //     return count;
    // };

    priceFlool(data) {
        var num = Number(data);
        if (data || data == "0") {
            num = num
                .toFixed(3)
                .substring(0, num.toFixed(3).toString().length - 1);
            return num;
        }
        return num;
    }

    //订单总额
    totalMoney = (data, minusPrice) => {
        if (!data) return;
        let totalMoney = 0;
        if ($state.params.groupbuyingId) {
            /* let count = Number($state.params.productCount)||1;
            let priceList = data&&data[0].staircasePriceModels||[];
            let priceObj=priceList.filter((v, k) => {
                if(v.maxLevel) {
                    return count>=v.maxAmount
                } else {
                     if(v.minAmount<count&&count<=v.maxAmount) {
                        return true;
                    }
                }
                
            });
            totalMoney = count*priceObj[0].price; */
            let count = Number($state.params.productCount) || 1;
            totalMoney = Number(data[0].showPrice) * count;
        } else {
            data &&
                data.forEach((v, k) => {
                    v.cart &&
                        v.cart.forEach((v1, k1) => {
                            totalMoney += v1.countPrice;
                        });
                });
        }
        this.totalPrice = Filter.float(totalMoney, 2);
        totalMoney = totalMoney - minusPrice;
        return this.priceFlool(totalMoney);
    };

    //运费总额
    totalCarryFee = data => {
        let totalMoney = 0;
        if (data && data.length) {
            data.forEach((v, k) => {
                totalMoney += v.totalCarryFee;
            });
        }
        return this.priceFlool(totalMoney);
    };

    initShoppingCarts = data => {
        let arr = [];
        if (data && data.length) {
            data.forEach((v, k) => {
                arr.push({
                    productSn: v.id,
                    supplierId: v.suppId,
                    amount: $state.params.productCount || 1
                });
            });
        }

        return arr;
    };

    //提交审批
    sumitClick(params) {
        // this.props.isShowCard
        if (["18", "37"].indexOf(this.orgId) > -1 || Uts.getCookie("orgCode")=="GUANG_DONG_SHI_YOU_HUA_GONG_XUE_YUAN") {
            if (!params.cardIds.length) {
                message.warn({
                    text: "请至少选择一张经费卡" || "",
                    width: 220,
                    duration: 3000
                });
                return;
            }
        }
        if (["38"].indexOf(this.orgId) > -1) {
            if (!params.piIds.length) {
                message.warn({
                    text: "请至少选择一个审批人" || "",
                    width: 220,
                    duration: 3000
                });
                return;
            }
        }
        if (Uts.getCookie("orgCode")=="GUANG_DONG_SHI_YOU_HUA_GONG_XUE_YUAN") {
            if (!this.state.textareaValue) {
                message.warn({
                    text: "请填写采购申请说明",
                    width: 220,
                    duration: 3000
                });
                return;
            }
        }

        // 课题组校验
        if (["3"].indexOf(this.orgId) == -1) {
            if (!params.department) {
                message.warn({
                    text: "请选择课题组",
                    duration: 3000
                });
                return;
            }
        }

        console.log(this.state.textareaValue,this.state.textareaValue.length)
        //采购申请说明字数限制
        if (this.state.textareaValue.length>200) {
            message.warn({
                text: "采购申请说明请控制在200字以内",
                width: 350,
                duration: 3000
            });
            return;
        }

        // this.checkData(params);
        console.log(params);
        let url = `/store/api/order/addPurchaseApply`;
        let _params = params;
        _params.applyInfo = this.state.textareaValue;
        _params.department.users = [];
        if ($state.params.groupbuyingId) {
            _params.groupBuyingId = $state.params.groupbuyingId;
            _params.shoppingCarts = this.initShoppingCarts(
                this.props.moneyData
            );
        }
        if(this.state.hasLabel&&_params.tdeliveryAddress.label ==""){
            this.props.labelEdit(_params.tdeliveryAddress.id);
            return;
        }
        ToastUtils.loading();
        /*if(_params.tdeliveryAddress.label!=undefined&&_params.tdeliveryAddress.label!=""&&(_params.tdeliveryAddress.remark==undefined||_params.tdeliveryAddress.remark=="")){
            _params.tdeliveryAddress.address = _params.tdeliveryAddress.deliveryAdress+"-"+_params.tdeliveryAddress.label;
        }else if(_params.tdeliveryAddress.label!=undefined&&_params.tdeliveryAddress.label!=""&&_params.tdeliveryAddress.remark!=undefined&&_params.tdeliveryAddress.remark!=""){
            _params.tdeliveryAddress.address = _params.tdeliveryAddress.deliveryAdress+"-"+_params.tdeliveryAddress.label+"("+_params.tdeliveryAddress.remark+")";
        }*/
        //只针对贵医大的选人不选卡入参piIds
        if (["38"].indexOf(this.orgId) == -1) {
            delete _params.piIds;
        }
        delete _params.tdeliveryAddress.label;
        delete _params.tdeliveryAddress.remark;
        delete _params.tdeliveryAddress.select;
        delete _params.tdeliveryAddress.default;
        delete _params.tdeliveryAddress.deliveryAdress;
        if (this.orgId == "3"&&_params.applyProductReqs&&_params.applyProductReqs.length>0) {
            if(Uts.findObjByCondition(params.applyProductReqs,{directoryId: 0}).length>0) {
                message.warn({
                    text: "请选择政府采购品目",
                    duration: 3000
                });
                ToastUtils.hide();
                return;
            }

            if (!this.props.ZDBetten) {
                message.warn({
                    text: "请阅读并提交《关联关系声明》" || "",
                    width: 280,
                    duration: 3000
                });
                ToastUtils.hide();
                return;
            }
            if (this.props.ZDBetten == "2" && !_params.relateInfo) {
                message.warn({
                    text: "请填写具体的关联关系" || "",
                    width: 280,
                    duration: 3000
                });
                ToastUtils.hide();
                return;
            }
        }
            REST.post(url, _params, "dis").then(
                data => {
                    ToastUtils.hide();
                    if (data.suppMsgs && data.suppMsgs.length > 0) {
                        if (this.orgId == "3") {
                            window.location.href = `${Uts.getCookie(
                                "HREF_FOR_ZD"
                            )}/#addCard?id=${data.id}`;
                        } else {
                            U.storage.set("POrderResult", data);
                            const { isGroupbuying } = this.props;
                            $state.go({
                                stateName: "/orderResults",
                                params: { isGroupbuying: isGroupbuying ? 1 : 0 }
                            });
                        }
                    } else {
                        if (data.code == "0009") {
                            this.showModal(data.message);
                        } else {
                            message.warn({
                                text: data.message || "",
                                duration: 3000
                            });
                        }
                    }
                },
                error => {
                    ToastUtils.hide();
                }
            );
    }

    showModal = message => {
        function closeModal(value) {
            console.log("run closeModal", value);
            modal.hide();
        }

        function Content(props) {
            props.item.passParams && props.item.passParams("abc");
            return (
                <div className="zen_fs-14 zen_h-180">
                    <div className="zen_t-c zen_m-b-20">
                        以下商品已下架或贵单位禁止采购，请重新选择商品
                    </div>
                    <div
                        className="zen_t-c zen_969696 rj_l-wp-m"
                        dangerouslySetInnerHTML={{ __html: message }}
                    />
                    <div className="zen_ps-ab zen_b-40 zen_l-140">
                        <span
                            className="zen_cur-p zen_p-h-40 zen_p-v-10 zen_bg-0093EB zen_bdr-4 zen_white"
                            onClick={closeModal}
                        >
                            知道了
                        </span>
                    </div>
                </div>
            );
        }
        let options = {
            header: "提示",
            modalClass: "zen_bdr-5",
            // footer: "test footer",
            content: Content,
            size: "sm",
            hideFooter: true,
            // cbList: [closeModal],
            close: closeModal
        };
        let modal = ZenModal.loadModal(options);
        modal.show();
    };

    render() {
        const { textareaValue } = this.state;
        const {
            formData,
            moneyData,
            minusPrice,
            serviceItem,
            commodityItem
        } = this.props;
        let totalMoney = this.totalMoney(moneyData, minusPrice);
        if(this.state.hasLabel!=this.props.hasLabel){
            this.setState({hasLabel:this.props.hasLabel})
        }
        console.log("ProcurementMoneyMount",this.state.hasLabel,this.props.hasLabel)
        // let totalCarryFee = this.totalCarryFee(moneyData);

        return (
            <div className="rj_procurement-wp">
                <div className="rj_procurement-info">
                    <div className="rj_l-textrea-wp">
                        <span className={Uts.getCookie("orgCode")=="GUANG_DONG_SHI_YOU_HUA_GONG_XUE_YUAN" ?"rj_l-textrea-title zen_fs-12 zen_m-t-5":"zen_fs-12 zen_m-t-5"}>
                            采购申请说明
                        </span>
                        <Textarea
                            className="rj_l-textrea zen_fs-12"
                            onChange={this.changeValue.bind(this)}
                            defaultValue={textareaValue}
                        />
                    </div>
                    <div className="rj_l-content-r">
                        <div>
                            <span className="rj_l-m-tittle">
                                <em>{commodityItem ? commodityItem : 1}</em>
                                <span>项商品，</span>
                                <em>{serviceItem ? serviceItem : "0"}</em>
                                <span>项服务，</span>
                                <span>订单总价：</span>
                            </span>
                            <span className="rj_l-m">
                                <em>￥</em>
                                {this.totalPrice}
                                {formData.totalCarryFee
                                    ? `(含运费￥${formData.totalCarryFee})`
                                    : ""}
                            </span>
                        </div>
                        {!$state.params.groupbuyingId && (
                            <div>
                                <span className="rj_l-m-tittle">
                                    商家优惠：
                                </span>
                                <span className="rj_l-m">
                                    {minusPrice > 0
                                        ? `-￥${minusPrice}`
                                        : `-￥0.00`}
                                </span>
                            </div>
                        )}

                        {/* <div>
                            <span className="rj_l-m-tittle">经费卡余额：</span>
                            <span className="rj_l-m">充足</span>
                        </div> */}
                        <div>
                            <span className="rj_l-m-tittle">应付总额：</span>
                            <span className="rj_l-m rj_lm-red">
                                <em>￥</em>
                                {totalMoney}
                            </span>
                        </div>
                        <div
                            className="rj_commit-btn"
                            onClick={this.props.isFrozen==0?this.sumitClick.bind(this, formData):""}
                        >
                            <Button type="error" disabled={this.props.isFrozen==0?false:true}>提交</Button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default ProcurementMoney;
